package kr.couponplay.android.activity.search;

import java.util.Date;
import java.util.List;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.query.RecentQuery;
import kr.couponplay.android.support.DateUtils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class QueryListAdapter extends ArrayAdapter<RecentQuery> {
	private Context mContext;
	private int mResource;
	private List<RecentQuery> recentQueries;
	private LayoutInflater mInflater;

	public QueryListAdapter(Context context, int layoutResource, List<RecentQuery> recentQueries) {
		super(context, layoutResource, recentQueries);
		this.mContext = context;
		this.mResource = layoutResource;
		this.recentQueries = recentQueries;
		this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		RecentQuery recentQuery = recentQueries.get(position);

		if (convertView == null) {
			convertView = mInflater.inflate(mResource, parent, false);
		}

		if (recentQuery != null) {
			TextView query = (TextView) convertView.findViewById(R.id.text_list_row_title_view);
			query.setText(recentQuery.getQuery());

			TextView date = (TextView) convertView.findViewById(R.id.text_list_row_date_view);
			date.setText(DateUtils.toString(new Date(Long.parseLong(recentQuery.getInsertDate()))));
			
			Button deleteBtn = (Button) convertView.findViewById(R.id.text_list_row_delete);
			DeleteOnClickListener deleteOnClickListener = new DeleteOnClickListener(mContext, this, position);
			deleteBtn.setOnClickListener(deleteOnClickListener);
		}
		return convertView;
	}
	
	public RecentQuery getItem(int position) {
		return recentQueries.get(position);
	}
	
	public int getItemSize() {
		return recentQueries.size();
	}
}
